package ar.edu.itba.tp1.gps.api;

import java.util.Arrays;

import ar.edu.itba.tp1.gps.GPSRun;

public class GPSStateImpl implements GPSState {
	private Integer[][] valuesMatrix;

	public GPSStateImpl() {
		valuesMatrix = new Integer[GPSRun.n][GPSRun.n];
	}
	
	@Override
	public void addValue (int i, int j, Integer value) {
		valuesMatrix[i][j] = value;
	}
	
	@Override
	public Integer[][] getValues() {
		return valuesMatrix;
	}
	
	public Integer getValue(int i, int j) {
		return valuesMatrix[i][j];
	}
	
	@Override
	public boolean compare(GPSState state) {
		Integer[][] otherValuesMatrix = state.getValues();
		for (int i = 0; i < valuesMatrix.length; i++) {
			for (int j = 0; j < valuesMatrix[i].length; j++) {
				if (valuesMatrix[i][j] != otherValuesMatrix[i][j]) {
					return false;
				}
			}
		}
		return true;
	}

	@Override
	public boolean isGoalState() {
		for (int i = 0; i < valuesMatrix.length; i++) {
			for (int j = 0; j < valuesMatrix[i].length; j++) {
				if (valuesMatrix[i][j] == null) {
					return false;
				}
			}
		}
		return true;
	}
	
	@Override
	public GPSState copyState () {
		GPSState newState = new GPSStateImpl();
		Integer[][] otherMatrix = newState.getValues();
		for (int i = 0; i < valuesMatrix.length; i++) {
			for (int j = 0; j < valuesMatrix[i].length; j++) {
				otherMatrix[i][j] = valuesMatrix[i][j];
			}
		}
		return newState;
	}
	
	@Override
	public String toString() {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append('[');
		Integer cellsFilled = 0;
		for (int i = 0; i < valuesMatrix.length; i++) {
			for (int j = 0; j < valuesMatrix[i].length; j++) {
				if (valuesMatrix[i][j] != null) {
					stringBuilder.append(valuesMatrix[i][j]);
					cellsFilled++;
				} else {
					stringBuilder.append('-');
				}
				if (j != valuesMatrix[i].length-1) {
					stringBuilder.append(',');
				}
			}
			stringBuilder.append(';');
		}
		stringBuilder.append(']').append(" - ").append(cellsFilled);
		return stringBuilder.toString();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + Arrays.hashCode(valuesMatrix);
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		GPSStateImpl other = (GPSStateImpl) obj;
		if (!Arrays.equals(valuesMatrix, other.valuesMatrix))
			return false;
		return true;
	}
	
}
